package top.infopub.mgr.flow.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.service.BidReviewService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.sys.service.OperatorService;
import top.infopub.mgr.util.OAUtil;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.BidReview;
import top.infopub.model.sys.Operator;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class OAFlowServiceImpl implements OAFlowService{

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private OperatorService operatorService;

    @Autowired
    private BidReviewService bidReviewService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Override
    public String sendOAToDo(String title, String sendUserId, String toUserId, String srcBizTable, String srcBizSguid) {
        // http://localhost:8080/mgr/sso?date=1609983279802&backUrl=http://localhost:8080/mgr/main&token=1937694_421ef99d1295c409d4dbf2e742352a5c
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String contextPath = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+contextPath+"/";
//        String backUrl=basePath+"mgr/main";
        String backUrl=basePath+bizControllerMapping(srcBizTable, srcBizSguid);

        StaffInfo createStaffInfo = getStaffInfoById(dealNameOf(sendUserId).getHrStaffId());
        StaffInfo toStaffInfo = getStaffInfoById(dealNameOf(toUserId).getHrStaffId());
        Map<String,String> oaMap=new HashMap<>();
        oaMap.put("titile",title);
        oaMap.put("createbyname",createStaffInfo.getName());
        oaMap.put("createbycode",createStaffInfo.getCode());
        oaMap.put("toname",toStaffInfo.getName());
        oaMap.put("tocode",toStaffInfo.getCode());
        oaMap.put("type","znjt");
        oaMap.put("url",basePath+"mgr/sso?backUrl="+backUrl);//处理公文页面链接
        oaMap.put("company",toStaffInfo.getOrgName());//公司名称
        JSONObject str = OAUtil.erpTodo(oaMap);
        System.out.println("调用OA接口返回：" + str.toString());
        boolean success = str.getBoolean("success");
        String oaId = "";
        if(success){
            oaId = str.getString("id");
            if(StringUtils.isEmpty(oaId)){
//                throw new FlowProcessException("发起OA待办失败，请联系管理员");
            }
        }else{
//            throw new FlowProcessException("发起OA待办失败，请联系管理员");
        }
        return oaId;
    }

    @Override
    public boolean finishOA(String id) {
        JSONObject str = OAUtil.finishOA(id);
        boolean success = str.getBoolean("success");
        if(success){
            return success;
        }else{
//            throw new FlowProcessException("处理OA待办失败，请联系管理员");
        }
        return false;
    }

    private Operator dealNameOf(String checkUserId) {
        Operator opt = operatorService.selectByPrimaryKey(checkUserId);
        if (opt == null) {
            return new Operator();
        }
        else {
            return opt;
        }
    }

    private StaffInfo getStaffInfoById(String staffId) {
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(staffId);
        if (staffInfo == null) {
            return new StaffInfo();
        }
        else {
            return staffInfo;
        }
    }

    /**
     * 生成 对应 跳转到各业务审核页面的controller方法
     * @param srcBizTable
     * @return
     * @see
     */
    private String bizControllerMapping(String srcBizTable, String srcBizSguid) {
        StringBuilder result = new StringBuilder();
        // 如把PRO_MASTER_INFO 转成 masterInfo
        String[] split = srcBizTable.split("_");
        StringBuilder buffer = new StringBuilder();
        buffer.append(split[1].toLowerCase());
        if (com.alibaba.druid.util.StringUtils.equals("MKT_BID_REVIEW", srcBizTable)) {
            BidReview bidReview = bidReviewService.selectById(srcBizSguid);
            if (bidReview != null) {
                if (com.alibaba.druid.util.StringUtils.equals("1", bidReview.getBidType())) {
                    result.append("creditDetails/toDealOrDetail?id=");
                } else if (com.alibaba.druid.util.StringUtils.equals("2", bidReview.getBidType())) {
                    result.append("business/toDealOrDetail?id=");
                } else if (com.alibaba.druid.util.StringUtils.equals("3", bidReview.getBidType())) {
                    result.append("technicalDetail/toDealOrDetail?id=");
                }
                result.append(srcBizSguid);
                result.append("&processDealWith=y&proCode=");
                result.append(bidReview.getProCode());
                result.append("&times=");
                result.append(System.currentTimeMillis());
                return result.toString();
            }
        }
        for (int i = 2; i < split.length; i++ ) {
            String lowerCaseSplit = split[i].toLowerCase();
            String firstUpperChar = (lowerCaseSplit.charAt(0) + "").toUpperCase();
            buffer.append(firstUpperChar + lowerCaseSplit.substring(1));
        }
        result.append(buffer);
        // 【注意】：所有业务表单，跳转到审核页面必须统一命名：toDealOrDetail
        String proCode = "";
        if (srcBizTable.startsWith("MKT_")) {
            try {
                proCode = proProcessManageService.getProCodeById(srcBizTable, srcBizSguid);
            } catch (Exception e) {

            }
        }
        result.append("/toDealOrDetail?id=");
        result.append(srcBizSguid);
        result.append("&processDealWith=y&proCode=");
        result.append(proCode);
        result.append("&times=");
        result.append(System.currentTimeMillis());
        return result.toString();
    }
}
